<template>
  <el-dialog
    :title="formData.id ? '编辑设备' : '新增设备'"
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    width="600px"
    :before-close="handleClose">
    
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px">
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="设备编码" prop="devCode">
            <el-input
              v-model="formData.devCode"
              placeholder="请输入设备编码"
              :disabled="!!formData.id" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备名称" prop="devName">
            <el-input
              v-model="formData.devName"
              placeholder="请输入设备名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="产线名称" prop="productionLine">
            <el-input
              v-model="formData.productionLine"
              placeholder="请输入产线名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备规格" prop="devSpec">
            <el-input
              v-model="formData.devSpec"
              placeholder="请输入设备规格" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="设备状态" prop="devStatus">
            <el-select
              v-model="formData.devStatus"
              placeholder="请选择设备状态"
              style="width: 100%">
              <el-option label="运行中" value="运行中" />
              <el-option label="停机" value="停机" />
              <el-option label="维修中" value="维修中" />
              <el-option label="报废" value="报废" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备管理人" prop="devManager">
            <el-input
              v-model="formData.devManager"
              placeholder="请输入设备管理人" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="购入时间" prop="buyTime">
        <el-date-picker
          v-model="formData.buyTime"
          type="date"
          placeholder="选择购入时间"
          style="width: 100%"
          value-format="YYYY-MM-DD" />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">
        {{ formData.id ? '更新' : '创建' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

// 定义 props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: () => ({})
  }
})

// 定义 emits
const emit = defineEmits(['update:visible', 'submit', 'close'])

// 响应式数据
const loading = ref(false)
const formRef = ref()

// 表单验证规则
const formRules = {
  devCode: [
    { required: true, message: '请输入设备编码', trigger: 'blur' },
    { min: 1, max: 50, message: '设备编码长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  devName: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
    { min: 1, max: 50, message: '设备名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  devStatus: [
    { required: true, message: '请选择设备状态', trigger: 'change' }
  ],
  productionLine: [
    { required: true, message: '请输入产线名称', trigger: 'blur' }
  ]
}

// 监听 visible 变化，重置表单验证
watch(() => props.visible, (newVal) => {
  if (newVal) {
    nextTick(() => {
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    })
  }
})

// 关闭弹窗
const handleClose = () => {
  emit('update:visible', false)
  emit('close')
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    // 表单验证
    await formRef.value.validate()
    
    loading.value = true
    // 创建表单数据的副本，避免直接修改props
    const submitData = JSON.parse(JSON.stringify(props.formData))
    
    // // 遍历所有字段，将空字符串转换为null
    // Object.keys(submitData).forEach(key => {
    //   if (submitData[key] === '') {
    //     submitData[key] = null
    //   }
    // })
    
    // 触发提交事件，传递表单数据
    emit('submit', submitData)
    
  } catch (error) {
    if (error.errors) {
      ElMessage.error('请完善表单信息')
    }
  } finally {
    loading.value = false
  }
}

// 暴露方法给父组件
defineExpose({
  setLoading: (value) => {
    loading.value = value
  }
})
</script>

<style scoped>
/* 弹窗样式优化 */
:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input-number) {
  width: 100%;
}
</style>